package com.smcdd.cdb.dbo.cdb_dbo.service.presenter;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;

import com.smcdd.cdb.dbo.cdb_dbo.R;
import com.smcdd.cdb.dbo.cdb_dbo.app.App;
import com.smcdd.cdb.dbo.cdb_dbo.service.entity.Address;
import com.smcdd.cdb.dbo.cdb_dbo.service.entity.BaseResponseEntity;
import com.smcdd.cdb.dbo.cdb_dbo.service.entity.Site;
import com.smcdd.cdb.dbo.cdb_dbo.service.entity.SitePosition;
import com.smcdd.cdb.dbo.cdb_dbo.service.entity.Tel;
import com.smcdd.cdb.dbo.cdb_dbo.service.entity.UploadImage;
import com.smcdd.cdb.dbo.cdb_dbo.service.entity.UrlEvent;
import com.smcdd.cdb.dbo.cdb_dbo.service.maneger.DataManager;
import com.smcdd.cdb.dbo.cdb_dbo.service.maneger.HttpUtil;
import com.smcdd.cdb.dbo.cdb_dbo.service.maneger.NetWorkCodeInfo;
import com.smcdd.cdb.dbo.cdb_dbo.service.view.IAddMenDianAc;
import com.smcdd.cdb.dbo.cdb_dbo.ui.activity.AddMenDianActivity;
import com.smcdd.cdb.dbo.cdb_dbo.ui.adapter.DemoGridAdapter;
import com.smcdd.cdb.dbo.cdb_dbo.ui.adapter.SitePopGridAdapter;
import com.smcdd.cdb.dbo.cdb_dbo.ui.base.BaseActivity;
import com.smcdd.cdb.dbo.cdb_dbo.ui.base.BasePresenter;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.AssetsAnalysis;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.DialogUtils;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.Encode;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.JsonUtil;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.ObtainEncry;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.ObtainVersion;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.ToastUtil;
import com.smcdd.cdb.dbo.cdb_dbo.ui.widget.AwaitDialog;
import com.smcdd.cdb.dbo.cdb_dbo.ui.widget.FlowLayout;
import com.smcdd.cdb.dbo.cdb_dbo.ui.widget.SelectPicPopupWindow;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * 作者：Administrator on 2017/6/20 15:04
 * 邮箱：zhanghuaiha@gmail.com
 */

public class AddMenDianPresenter extends BasePresenter<IAddMenDianAc> {

    private AddMenDianActivity addMenDianActivity;
    private SelectPicPopupWindow menuWindow;
    private Site site;
    private List<Site.DataBean> data;
    private  int cont = 0;
    private TextView site1;
    private DataManager manager;
    private CompositeSubscription mCompositeSubscription;
    private String udid;
    private String eid;
    private String versionName;
    private Dialog dialog;

    public AddMenDianPresenter(BaseActivity context) {
        super(context);
    }

    public void loadContacts(){
        udid = App.SP.getString("udid", "");
        eid = App.SP.getString("id", "");
        versionName = ObtainVersion.getVersionName(mContext);
        manager = new DataManager(mContext);
        mCompositeSubscription = new CompositeSubscription();
        addMenDianActivity = getView().getAddMenDianActivity();
        site1 = getView().getSite();
        //获取raw下的json文件并解析
        String json = AssetsAnalysis.getData(addMenDianActivity.getResources().openRawResource(R.raw.position));
        if (json != null) {
            site = JsonUtil.parseJsonToBean(json, Site.class);
        }
        data = site.getData();
    }

    //更新店铺
    public void update(String id,String name,String contact,String tel,String latitude,String longitude,String province_id,String city_id,String area_id,String specific_address,String province_name,String city_name,String area_name,String position,String position_name,String img_url,String from_type,String remark){
        String time = System.currentTimeMillis() + "";
        String encry = ObtainEncry.update("2",time,versionName,NetWorkCodeInfo.UPDATE,udid,id,eid,name,contact,tel,latitude,longitude,province_id,city_id,area_id,specific_address,province_name,city_name,area_name,position,position_name,img_url,from_type,remark);
        mCompositeSubscription.add(manager.update("2",time,versionName,NetWorkCodeInfo.UPDATE,udid,id,eid,name,contact,tel,latitude,longitude,province_id,city_id,area_id,specific_address,province_name,city_name,area_name,position,position_name,img_url,from_type,remark,encry)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseResponseEntity>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        ToastUtil.showToast("添加门店失败");
                        EventBus.getDefault().post("update");
                        addMenDianActivity.finish();
                    }

                    @Override
                    public void onNext(BaseResponseEntity tel) {
                        getView().getDialog().dismiss();
                        Log.e("AddMenDianPresenter",tel.code+"");
                        if (tel.code == 200) {
                            ToastUtil.showToast("添加门店成功");
                            EventBus.getDefault().post("update");
                            addMenDianActivity.finish();
                        }else {
                            ToastUtil.showToast(tel.message);
                        }
                    }
                }));
    }



    //新增店铺
    public void insert(String name,String contact,String tel,String latitude,String longitude,String province_id,String city_id,String area_id,String specific_address,String province_name,String city_name,String area_name,String position,String position_name,String img_url,String from_type,String remark){
        String time = System.currentTimeMillis() + "";
        String encry = ObtainEncry.insert("2",time,versionName,NetWorkCodeInfo.INSERT,udid,eid,name,contact,tel,latitude,longitude,province_id,city_id,area_id,specific_address,province_name,city_name,area_name,position,position_name,img_url,from_type,remark);
        mCompositeSubscription.add(manager.insert("2",time,versionName,NetWorkCodeInfo.INSERT,udid,eid,name,contact,tel,latitude,longitude,province_id,city_id,area_id,specific_address,province_name,city_name,area_name,position,position_name,img_url,from_type,remark,encry)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Observer<BaseResponseEntity>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                Log.e("AddMenDianPresenter",e.toString());
                ToastUtil.showToast("添加门店失败");
                EventBus.getDefault().post("refresh");
                addMenDianActivity.finish();
            }

            @Override
            public void onNext(BaseResponseEntity tel) {
                getView().getDialog().dismiss();
                Log.e("AddMenDianPresenter",tel.code+"");
                if (tel.code == 200) {
                    ToastUtil.showToast("添加门店成功");
                    EventBus.getDefault().post("refresh");
                    addMenDianActivity.finish();
                }else {
                    ToastUtil.showToast(tel.message);
                }
            }
        }));
    }



    //上传照片
    public void uploadImage(File file){
        dialog();
        RequestBody requestFile =
                RequestBody.create(MediaType.parse("image/png"), file);
        String time = System.currentTimeMillis() +"";
        String encry = ObtainEncry.uploadImage(NetWorkCodeInfo.UPLOAD_IMAGE,"2",time,udid,versionName);
        Map<String, RequestBody> map = new LinkedHashMap<>();
        map.put("encry",toRequestBody(encry));
        map.put("i",toRequestBody(NetWorkCodeInfo.UPLOAD_IMAGE));
        map.put("rf",toRequestBody("2"));
        map.put("ts",toRequestBody(time));
        map.put("udid",toRequestBody(udid));
        map.put("v",toRequestBody(versionName));
        map.put("file\";filename=\""+file.getName(),requestFile);
        mCompositeSubscription.add(manager.uploadImages(map)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Observer<UploadImage>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.showToast("图片上传失败....");
                dialog.dismiss();
            }

            @Override
            public void onNext(UploadImage uploadImage) {
                dialog.dismiss();
                if (uploadImage.getCode() == 200) {
                    String url = uploadImage.getData();
                    EventBus.getDefault().post(new UrlEvent(url));
                }else {
                    ToastUtil.showToast("图片上传失败");
                }

            }
        }));

    }

    public static RequestBody toRequestBody(String value) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain"), value);
        return requestBody;
    }


    public void unLoadData(){
        if (mCompositeSubscription.hasSubscriptions()){
            mCompositeSubscription.unsubscribe();
        }
    }

    public void dialog(){
        dialog = DialogUtils.uploadDialog(mContext, "正在上传图片.", false);
    }


    /*
        PopupWindow展示
        */
    public void select() {

        ((InputMethodManager) addMenDianActivity.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(addMenDianActivity.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        menuWindow = new SelectPicPopupWindow(addMenDianActivity) {

            @Override
            public View initView() {
                LayoutInflater inflater = (LayoutInflater) addMenDianActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                View menuview = inflater.inflate(R.layout.item_site_popupwindows, null);

                GridView gv = (GridView) menuview.findViewById(R.id.site_popup_gv);
                TextView end = (TextView) menuview.findViewById(R.id.site_popup_end);
                TextView save = (TextView) menuview.findViewById(R.id.site_popup_save);
                gv.setAdapter(new SitePopGridAdapter(mContext,data));
                gv.setOnItemClickListener((parent, view, position, id) -> {
                    view.setSelected(true);
                    cont = position;
                });
                save.setOnClickListener(v -> {
                    site1.setText(data.get(cont).getName());
                    EventBus.getDefault().post(new SitePosition(data.get(cont).getId(),data.get(cont).getName()));
                    dismiss();});
                /**
                 * 取消按钮销毁事件
                 * by黄海杰@2015-1-7
                 */
                end.setOnClickListener(v ->  dismiss());
                return menuview;
            }
        };
        //设置弹窗位置
        menuWindow.showAtLocation(addMenDianActivity.findViewById(R.id.add), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }
}
